package com.rongke.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.rongke.commons.JsonResp;
import com.rongke.mapper.MessageMapper;
import com.rongke.model.Message;
import com.rongke.model.MsgUser;
import com.rongke.model.Muser;
import com.rongke.service.MessageService;

import com.rongke.service.MsgUserService;
import com.rongke.service.MuserService;
import com.rongke.utils.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.*;

/**
 * @version : Ver 1.0
 * @MessageController
 * @消息Controller
 */
@RestController
@RequestMapping(value = "/api/message")
@Transactional
@CrossOrigin
public class MessageController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private MessageService messageService;
    @Autowired
    private MsgUserService msgUserService;
    @Autowired
    private MuserService muserService;

    /**
     * @param message
     * @return 返回值JsonResp
     * @添加消息
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public JsonResp addMessage(@RequestBody Message message) {

        log.debug("添加消息");
        message.setGmtDatetime(new Date());
        messageService.insert(message);
/*        //获取推送用户id列表
        EntityWrapper<Muser> ewm = new EntityWrapper<>();
        ewm.isNotNull("user_name");
        ewm.setSqlSelect("id");
        List<Object> ids = muserService.selectObjs(ewm);
        if(null!=ids&&!ids.isEmpty()){
            Map condition = new HashMap();
            condition.put("msgId", message.getId());
            condition.put("userIds", ids);
//        long start=System.currentTimeMillis();
            msgUserService.insertBatchMsg(condition);
//        long end=System.currentTimeMillis();
//        System.out.println("插入消息条数:"+ids.size());
//        System.out.println("执行时间"+(start-end)+"ms");
        }*/
        return JsonResp.ok(message);
    }

    /**
     * @param message
     * @return 返回值JsonResp
     * @修改消息
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public JsonResp updateMessage(@RequestBody Message message) {
        log.debug("修改消息");
        message.setUptDatetime(new Date());
        messageService.updateById(message);
        return JsonResp.ok(message);
    }

    /**
     * @param id
     * @return 返回值JsonResp
     * @根据id查找消息
     */
    @RequestMapping(value = "/selectOne", method = RequestMethod.GET)
    public JsonResp selectMessage(Long id) {
        log.debug("查找消息");
        Message message = messageService.selectById(id);
        return JsonResp.ok(message);
    }

    /**
     * @param message
     * @return 返回值JsonResp
     * @根据条件查找消息
     */
    @RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
    public JsonResp selectMessageByCondition(@RequestBody Message message) {
        log.debug("根据条件查找消息");
        if (message == null)
            return JsonResp.toFail("参数不能为空");
        List<Message> messageList = messageService.selectByCondition(message);
        return JsonResp.ok(messageList);
    }

    /**
     * 删除消息
     * @param id
     * @return
     */
    @RequestMapping(value = "/delMsg", method = RequestMethod.GET)
    public JsonResp delMsg(Long id){
        log.debug("删除消息");
        messageService.deleteById(id);
        return JsonResp.ok("删除成功");
    }

    /**
     * 获取某用户未读、部分已读消息列表
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/getUnreadMsgByUserId", method = RequestMethod.GET)
    public JsonResp getUnreadMsgByUserId(Long muserId,Page<MsgUser> page) {
        log.debug("获取某用户未读、部分已读消息列表");
        if(null==muserId||0==muserId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<MsgUser> ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        ew.eq("is_read",1);
        Integer readCount=msgUserService.selectCount(ew);
        //当已读数大于15时删除5条
        if(readCount>20){
            Page<MsgUser> pg=new Page<>(1,5);
            ew.orderBy("gmt_datetime");
            List<MsgUser> msgUsers=msgUserService.selectPage(pg,ew).getRecords();
            List<Long> ids=new ArrayList<>();
            msgUsers.forEach(e->{
                ids.add(e.getId());
            });
            msgUserService.deleteBatchIds(ids);
        }
        EntityWrapper<MsgUser> ewu=new EntityWrapper<>();
        ewu.eq("muser_id",muserId);
        ewu.orderBy("is_read");//未读在前
        ewu.orderBy("gmt_datetime",false);
        page=msgUserService.selectPage(page,ewu);
        if(!page.getRecords().isEmpty()){
            page.getRecords().forEach(e->{
                if(null!=e.getMsgId()){
                    e.setMsgContent(messageService.selectById(e.getMsgId()).getContent());
                    e.setTitle(messageService.selectById(e.getMsgId()).getTitle());
                }
            });
        }
        return JsonResp.ok(page);
    }

    /**
     * 用户读取未读消息
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/readOnesMsg",method = RequestMethod.GET)
    public JsonResp readOnesMsg(Long muserId,Long muId){
        log.debug("用户读取未读消息");
        if(null==muserId||0==muserId)
            return JsonResp.toFail("参数不能为空");
        EntityWrapper<MsgUser> ew=new EntityWrapper<>();
        ew.eq("id",muId);
        ew.eq("muser_id",muserId);
        ew.eq("is_read",0);
        List<MsgUser> msgUsers=msgUserService.selectList(ew);
        if(!msgUsers.isEmpty()){
            msgUsers.forEach(e->{
                e.setIsRead(1);
            });
            msgUserService.updateBatchById(msgUsers);
        }
        return JsonResp.ok(msgUsers);
    }

    /**
     * 用户获取未读消息数量以及最后一条消息的内容
     * @param muserId
     * @return
     */
    @RequestMapping(value = "/getUnreadCountandLastMsg",method = RequestMethod.GET)
    public JsonResp getUnreadCountandLastMsg(Long muserId){
        log.debug("用户获取未读消息数量以及最后一条消息的内容");
        EntityWrapper<MsgUser> ew=new EntityWrapper<>();
        ew.eq("muser_id",muserId);
        ew.eq("is_read",0);
        Integer unreadCount=msgUserService.selectCount(ew);
        MsgUser lastMsg=null;
        Page<MsgUser> pg=new Page<>(1,1);
        ew.orderBy("gmt_datetime",false);
        List<MsgUser> msgUsers=msgUserService.selectPage(pg,ew).getRecords();
        if(!msgUsers.isEmpty()){
            lastMsg=msgUsers.get(0);
            if(null!=lastMsg.getMsgId()){
                lastMsg.setTitle(messageService.selectById(lastMsg.getMsgId()).getTitle());
                lastMsg.setMsgContent(messageService.selectById(lastMsg.getMsgId()).getContent());
            }
        }
        Map map=new HashMap();
        map.put("unreadCount",unreadCount);
        map.put("lastMsg",lastMsg);
        return JsonResp.ok(map);
    }


    /**
     * 后台获取消息列表
     * @param page
     * @return
     */
    @RequestMapping(value = "/fetchMsgListAdmin",method = RequestMethod.POST)
    public JsonResp fetchMsgListAdmin(@RequestBody Page<Message> page){
        log.debug("后台获取消息列表");
        String search=page.getCondition().get("searchText").toString();
        EntityWrapper<Message> ew=new EntityWrapper<>();
        if(StringUtil.isNotEmpty(search)){
            ew.like("title",search);
        }
        String msgType=page.getCondition().get("msgType").toString();
        if("sys".equals(msgType)){
            ew.eq("message_type",0);
        }else{
            ew.ne("message_type",0);
        }
        page.setCondition(null);
        ew.orderBy("gmt_datetime",false);
        page=messageService.selectPage(page,ew);
        return JsonResp.ok(page);
    }
}
